// 导入 请求

import ajax from "../../../until/request.js"

import { searchValue, renderNav, lazyImg, goRmd1, getDoms, top } from '../../public/js/public.js'



// 购物车
class ShoppingCar {

  constructor() {
    this.init()
  }
  init () {
    window.onload = () => { lazyImg() }
    // this.getDoms()
    this.doms = getDoms({
      swiper: ".swiper",
      tbody: "tbody",
      tfoot: "tfoot",
    })
    // 获取搜索框
    this.search = document.querySelector("#search")
    this.searchBtn = document.querySelector("#searchBtn")
    top()
    // 获取 userInfo
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
    this.getCarData()
    this.tfootFn()
    this.searchValue()
    this.renderSwiper()
    goRmd1(this.doms.swiper, this.userInfo)
    window.addEventListener("scroll", lazyImg)

  }

  // 获取购物车的数据
  getCarData () {
    // 获取 user 加入购物车数据
    ajax.getPro({
      url: " http://localhost:8888/cart/list",
      params: {
        id: this.userInfo.user_id
      }
    }).then(res => {
      this.carList = JSON.parse(res).cart
      this.renderCarData()
      this.renderFoot()
    })

  }
  renderCarData () {
    // console.log(this.carList)
    let tbodyData = this.carList.map(item => {
      const { goods_id, cart_number, current_price, goods_number, imgSmall_logo, is_select, is_sale, title, sale_type } = item
      return `
       <tr>
            <th scope="row"><input class="form-check-input check" type="checkbox" value="" id="flexCheckChecked"
               ${is_select ? "checked" : ""}   data-id="${goods_id}">
            </th>
            <td>
              <img src=""  data-src ="${imgSmall_logo}" class="lazyImg"  alt="">        
              <div class="title">${title}</div>
            </td>
            <td class="price"> <span class="is_sale">${is_sale ? `打折${100 - parseInt(sale_type)}%` : ""}</span>  ¥${current_price}</td >
            <td><button type="button" class="btn btn-light sub" data-id="${goods_id} ">-</button>
           <input type="text" value="${cart_number}" class="cart_number" disabled="true" data-id="${goods_id} ">
          <button type="button" class="btn btn-light add " data-id="${goods_id}">+</button>
         <span class="goods_number">库存: <b>${goods_number}</b> </span>
          </td>
            </td >
            <td><span class="subtotal">¥${(cart_number * current_price).toFixed(2)}</span></td>
            <td><span class="collect">
                收藏
              </span>
              <span data-id="${goods_id}" class="del">
                删除
              </span>
            </td>
          </tr >
      `
    })
    this.doms.tbody.innerHTML = tbodyData.join("")
    this.update()
    lazyImg()
  }
  update () {
    // 事件委托
    // console.log(this.tbody)
    this.doms.tbody.onclick = (e) => {
      const target = e.target
      const targetId = target.dataset.id
      // 删除
      if (target.classList.contains("del")) {
        // 删除商品
        this.delGoods(target.dataset.id)
      }
      // 增加
      if (target.classList.contains("add")) {
        let num = target.parentElement.querySelector(".cart_number").value
        let goods_number = target.parentElement.querySelector(".goods_number").innerText.split(":")[1].trim()
        // 增加商品数量
        if (num >= goods_number) return
        num++
        this.addGoods(target.dataset.id, num)
      }
      //减少
      if (target.classList.contains("sub")) {
        let num = target.parentElement.querySelector(".cart_number").value
        let goods_number = target.parentElement.querySelector(".goods_number").innerText.split(":")[1].trim()

        if (num <= 0) return
        num--
        // 减少商品数量
        this.subGoods(target.dataset.id, num)
      }
      // 改变勾选状态
      if (target.classList.contains("check")) {
        this.selectGoods(target.dataset.id)

      }
    }
  }
  // 删除商品
  delGoods (goods_id) {
    ajax.getPro({
      url: "http://localhost:8888/cart/remove",
      params: {
        id: this.userInfo.user_id,
        goodsId: goods_id
      }
    }).then(res => {
      // console.log(res)
      // 获取数据 重新渲染页面
      this.getCarData()
    })
  }
  // 增加商品数量
  addGoods (goods_id, num) {
    ajax.postProToken({
      url: "http://localhost:8888/cart/number",
      params: {
        id: this.userInfo.user_id,
        goodsId: goods_id,
        number: num - 0,
        token: this.userInfo.token
      }
    }).then(res => {
      // console.log(res)
      // 重新渲染页面
      this.getCarData()
    })
  }
  // 减少商品数量
  subGoods (goods_id, num) {
    ajax.postProToken({
      url: "http://localhost:8888/cart/number",
      params: {
        id: this.userInfo.user_id,
        goodsId: goods_id,
        number: num - 0,
        token: this.userInfo.token
      }
    }).then(res => {
      // console.log(res)
      // 重新渲染页面
      this.getCarData()
    })
  }
  selectGoods (goods_id) {
    ajax.postProToken({
      url: "http://localhost:8888/cart/select",
      params: {
        id: this.userInfo.user_id,
        goodsId: goods_id,
        token: this.userInfo.token
      }
    }).then(res => {
      console.log(res)
      // 重新渲染页面
      this.getCarData()
    })
  }
  // foot 里面的 功能
  tfootFn () {
    this.doms.tfoot.addEventListener("click", e => {
      let target = e.target
      if (target.classList.contains("checkAll")) {
        this.selectAll()
      }
      if (target.classList.contains("delAll")) {
        this.delAll()
      }
    })
  }
  selectAll () {

    let type = this.tfoot.querySelector(".checkAll").checked ? 1 : 0
    ajax.postProToken({
      url: "http://localhost:8888/cart/select/all",
      params: {
        id: this.userInfo.user_id,
        type: type,
        token: this.userInfo.token
      }
    }).then(res => {
      console.log(res)
      // 重新渲染页面

      this.getCarData()
    })
  }
  delAll () {
    ajax.getPro({
      url: "http://localhost:8888/cart/remove/select",
      params: {
        id: this.userInfo.usr_id,
      }
    }).then(res => {
      // console.log(res)
      // 重新渲染页面
      this.getCarData()
    })
  }
  renderFoot () {
    // console.log(this.carList)
    // 总价  总数  选择数
    let totalPrice = 0
    let totalNum = 0
    let checkNum = 0
    let discount = 0
    let checkAll = 0
    this.carList.forEach(item => {
      const { is_select, price, current_price, cart_number } = item

      totalNum += parseInt(cart_number)
      if (is_select) {
        discount += parseInt(price) - parseInt(current_price)
        checkNum += cart_number
        checkAll++
        totalPrice += parseInt(current_price) * parseInt(cart_number)
      };
    })
    this.doms.tfoot.querySelector(".checkAll").checked = checkAll === this.carList.length ? true : false
    this.doms.tfoot.querySelector(".totalPrice").innerHTML = "¥ " + totalPrice.toFixed(2)
    this.doms.tfoot.querySelector(".totalNum").innerHTML = totalNum
    this.doms.tfoot.querySelector(".checkNum").innerHTML = checkNum
    this.doms.tfoot.querySelector(".disCount").innerHTML = "-" + discount
  }

  //搜索功能
  searchValue () {
    this.searchValue = searchValue
    this.searchValue()
  }

  // 渲染 轮播 精彩推荐
  renderSwiper () {
    // 请求数据 
    ajax.getPro({
      url: 'http://localhost:8888/goods/list',
      params: {
        pagesize: 1000, // 每页多少条数据
      }
    }).then(res => {
      // 获取 swiper 
      let swiperSlide = document.querySelectorAll(".swiper-slide")
      swiperSlide.forEach((item) => {

        renderNav(JSON.parse(res).list, ["新品"], item, 4)
      })

    })
  }

}


let shoppingCar = new ShoppingCar()



export default shoppingCar